/*
 * Copyright (c) 2025 CAX Conversion Project
 */
package com.comac.ins.common.core.config;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import com.comac.ins.common.core.decorator.ContextCopyingDecorator;

/**
 * 事件异步线程配置
 * @author zhanghongyi
 * @date 2024/7/5 16:44
 * @description BizEventAsyncThreadPoolConfig
 */
@EnableAsync
@Configuration
public class BizEventAsyncThreadPoolConfig {

    /**
     * 自定义异步执行使用的线程池保证上下文的传递
     */
    @Bean("bizEventListenerAsyncExecutor")
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(20);
        executor.setKeepAliveSeconds(60);
        executor.setQueueCapacity(1000);
        executor.setTaskDecorator(new ContextCopyingDecorator());
        executor.setThreadNamePrefix("BizEventAsync-Pool-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

}
